package org.nowcoder.leetcode.stack;

import java.util.ArrayDeque;
import java.util.Deque;

/**
 * Title  : 71. Simplify Path
 * Source : https://leetcode.cn/problems/simplify-path/?envType=study-plan-v2&envId=top-interview-150
 * Author : XrazYang
 * Date   : 2023-07-11
 */

public class LeetCode_71 {
    public String simplifyPath(String path) {
        Deque<String> sta = new ArrayDeque<>();
        String[] paths = path.split("/");
        for (String name : paths) {
            if (name.length() > 0) {
                if ("..".equals(name)) {
                    if (!sta.isEmpty()) {
                        sta.pollLast();
                    }
                } else {
                    if (!".".equals(name)) {
                        sta.offerLast(name);
                    }
                }
            }
        }

        //路径拼接： 倒序(此处代码有点丑陋)
        // StringBuilder builder = new StringBuilder();
        // int i = sta.size();
        // String[] strs = new String[i];
        // while (!sta.isEmpty()) {
        //     strs[--i] = sta.pop();
        // }
        // for (String str : strs) {
        //     builder.append("/");
        //     builder.append(str);
        // }
        // return builder.length() == 0 ? "/" : builder.toString();

        StringBuilder builder = new StringBuilder();
        if (sta.isEmpty()) {
            builder.append("/");
        } else {
            while (!sta.isEmpty()) {
                builder.append("/");
                builder.append(sta.pollFirst());
            }
        }
        return builder.toString();
    }
}
